import React, { Component, FC, useState, useEffect, useRef } from 'react'
import { Table, Tag, Space, Button, Input, Row, Col, Modal } from 'antd'
import * as echarts from 'echarts'
import { set_list, fetchTest } from './homeSlice'
import { useAppDispatch, useAppSelector } from 'store/hooks'

import { getTableList } from './homeApi'
const HomePage: FC = () => {
  const [list, setList] = useState<any[]>([])
  const [total, setTotal] = useState<number>(0)
  const [visible, setVisible] = useState<boolean>(false)
  const echartDom = useRef<HTMLDivElement | null>(null)
  const [pv, setPv] = useState<number[]>([])
  const [publishTimeArr, setPublishTimeArr] = useState<any[]>([])

  const dispatch = useAppDispatch()
  const store = useAppSelector((s) => s.home)

  useEffect(() => {
    getList()
  }, [])

  const getList = async () => {
    const data = await getTableList({})
    // console.log('data:', data.data)
    const arr: number[] = []
    const brr: any[] = []
    data.data.list.forEach((item: any) => {
      arr.push(item.pv)
      brr.push(item.publishTime)
    })
    setPv(arr)
    setPublishTimeArr(brr)

    setTotal(data.data.total)
    setList(data.data.list)
  }

  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([])
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render(text: number) {
        return <>{text === 1 ? <Tag color={'green'}>已发布</Tag> : <Tag color={'red'}>草稿</Tag>}</>
      },
    },
    // {
    //   title: '',
    //   dataIndex: 'star',
    //   key: 'star',
    //   render(text: number) {
    //     return <Tag color={'red'}>{text}</Tag>
    //   },
    // },
    {
      title: '访问量',
      dataIndex: 'pv',
      key: 'pv',
      render(text: number) {
        return <Tag color={'red'}>{text}</Tag>
      },
    },
    {
      title: '标题',
      dataIndex: 'tag',
      key: 'tag',
      render(tags: any) {
        // console.log(tags, 'tags')
        return (
          <>
            {tags.map((tag: any) => {
              let color = tag.length > 5 ? 'geekblue' : 'green'
              if (tag === 'loser') {
                color = 'volcano'
              }
              // console.log(color, 'color')
              return (
                <Tag color={color} key={tag}>
                  {tag.toUpperCase()}
                </Tag>
              )
            })}
          </>
        )
      },
    },
    {
      title: 'Action',
      key: 'action',
      render: (text: any, record: any) => (
        <Space size="middle">
          <a>编辑 </a>
          <a
            onClick={() => {
              setVisible(true)
            }}
          >
            查看访问{' '}
          </a>
          <a>删除</a>
        </Space>
      ),
    },
  ]

  // const tableData = [
  //   {
  //     id: 1,
  //     key: 1,
  //     title: '飞狐外传',
  //     status: 1, // 0 草稿 1： 已经发布
  //     tag: ['武侠', '言情', '清宫'],
  //     star: 1,
  //     publishTime: '1648803138679',
  //   },
  //   {
  //     id: 2,
  //     key: 2,
  //     title: '雪山飞狐',
  //     status: 0, // 0 草稿 1： 已经发布
  //     tag: ['武侠言情心境', '言情', '清宫', '清宫2'],
  //     star: 1,
  //     publishTime: '1648803138679',
  //   },
  //   {
  //     id: 3,
  //     key: 3,
  //     title: '连城诀',
  //     status: 1, // 0 草稿 1： 已经发布
  //     tag: ['武侠', '言情', '清宫'],
  //     star: 1,
  //     publishTime: '1648803138679',
  //   },
  //   {
  //     id: 4,
  //     key: 4,
  //     title: '天龙八部',
  //     status: 1, // 0 草稿 1： 已经发布
  //     tag: ['武侠', '言情', '清宫'],
  //     star: 1,
  //     publishTime: '1648803138679',
  //   },
  //   {
  //     id: 5,
  //     key: 5,
  //     title: '射雕英雄传',
  //     status: 1, // 0 草稿 1： 已经发布
  //     tag: ['武侠', '言情', '清宫'],
  //     star: 1,
  //     publishTime: '1648803138679',
  //   },
  //   {
  //     id: 6,
  //     key: 6,
  //     title: '白马啸西风',
  //     status: 1, // 0 草稿 1： 已经发布
  //     tag: ['武侠', '言情', '清宫'],
  //     star: 1,
  //     publishTime: '1648803138679',
  //   },
  //   {
  //     id: 7,
  //     key: 7,
  //     title: '鹿鼎记',
  //     status: 1, // 0 草稿 1： 已经发布
  //     tag: ['武侠', '言情', '清宫'],
  //     star: 1,
  //     publishTime: '1648803138679',
  //   },
  // ]
  const onSelectChange = (selectedRowKeys: any[]) => {
    // console.log('selectedRowKeys changed: ', selectedRowKeys)
    setSelectedRowKeys(selectedRowKeys)
  }
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  }

  useEffect(() => {
    // 绘制echarts
    if (visible) {
      drawEcharts()
    }
  }, [visible])

  const drawEcharts = () => {
    if (echartDom.current) {
      const dom = document.getElementById((echartDom.current as any).id)
      if (dom) {
        const myChart = echarts.init(dom)
        const option = {
          tooltip: {
            trigger: 'axis',
            position: function (pt: any) {
              return [pt[0], '10%']
            },
          },
          title: {
            left: 'center',
            text: 'Large Area Chart',
          },
          toolbox: {
            feature: {
              dataZoom: {
                yAxisIndex: 'none',
              },
              restore: {},
              saveAsImage: {},
            },
          },
          xAxis: {
            type: 'category',
            boundaryGap: false,
            data: publishTimeArr,
          },
          yAxis: {
            type: 'value',
            boundaryGap: [0, '100%'],
          },
          // dataZoom: [
          //   {
          //     type: 'inside',
          //     start: 0,
          //     end: 10,
          //   },
          //   {
          //     start: 0,
          //     end: 10,
          //   },
          // ],
          series: [
            {
              name: 'Fake Data',
              type: 'line',
              symbol: 'none',
              sampling: 'lttb',
              itemStyle: {
                color: 'rgb(255, 70, 131)',
              },
              areaStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: 'rgb(255, 158, 68)',
                  },
                  {
                    offset: 1,
                    color: 'rgb(255, 70, 131)',
                  },
                ]),
              },
              data: pv,
            },
          ],
        }
        myChart.setOption(option)
      }
    }
  }

  return (
    <div>
      <button
        onClick={() => {
          dispatch(set_list(['list-------']))

          // dispatch(fetchTest()).then((res: any) => {
          //   console.log(res, 'rse')
          // })
        }}
      >
        home--test-提交
      </button>
      {/* Modal-start */}
      <Modal
        onOk={() => {
          setVisible(false)
        }}
        onCancel={() => {
          setVisible(false)
        }}
        visible={visible}
      >
        <div ref={echartDom} id="main" style={{ width: 500, height: 350 }} className="echarts-box"></div>
      </Modal>

      {/* model-end */}
      <Row>
        <Col span="6">
          Home-Page 标题 ：<Input />
        </Col>
        <Col span="6">
          状态 ：<Input />
        </Col>
        <Col span="6">
          分类 ：<Input />
        </Col>
      </Row>
      <Row>
        <Col>
          <Button type="primary">搜索</Button>
          <Button type="ghost">重置</Button>
        </Col>
      </Row>

      <Row>
        <Col>
          <Button type="primary">发布</Button>
          <Button type="ghost">删除</Button>
        </Col>
      </Row>

      <Row>
        <Col>
          <Table rowSelection={rowSelection} dataSource={list} columns={columns} />
        </Col>
      </Row>
    </div>
  )
}

export default HomePage
